<script lang="ts" setup>
import { getUserProfile, updateUserProfile } from '@/api/system/user/user.js'
import { useUserStore } from '@/store'
import { toastSuccess } from '@/utils/common'

definePage({
  style: {
    navigationBarTitleText: '个人信息',
  },
})

const form = ref()

const user = ref({
  nickName: '',
  phonenumber: '',
  email: '',
  sex: '',
})

const sexRange = [{
  label: '男',
  value: '0',
}, {
  label: '女',
  value: '1',
}]

function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        updateUserProfile(user.value).then(() => {
          toastSuccess('修改成功')
          useUserStore().fetchUserInfo()
          uni.navigateBack()
        })
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

function getUser() {
  getUserProfile().then((response) => {
    user.value = response.data.user
  })
}

getUser()
</script>

<template>
  <view class="page">
    <wd-form ref="form" :model="user" error-type="toast">
      <wd-cell-group border>
        <wd-input
          v-model="user.nickName"
          label="昵称"
          label-width="100px"
          prop="nickName"
          clearable
          placeholder="请输入昵称"
          :rules="[{ required: true, message: '请填写昵称' }]"
        />
        <wd-input
          v-model="user.phonenumber"
          label="手机号码"
          label-width="100px"
          prop="phonenumber"
          clearable
          placeholder="请输入手机号码"
          :rules="[{ required: true, message: '请填写手机号码' }]"
        />
        <wd-input
          v-model="user.email"
          label="邮箱"
          label-width="100px"
          prop="email"
          clearable
          placeholder="请输入邮箱"
          :rules="[{ required: true, message: '请填写邮箱' }]"
        />
        <wd-picker
          v-model="user.sex" label="性别"
          label-width="100px"
          prop="sex" :columns="sexRange"
          clearable
          placeholder="请输入性别"
          :rules="[{ required: true, message: '请填写性别' }]"
        />
      </wd-cell-group>
      <view class="page-content">
        <wd-button type="primary" block @click="handleSubmit">
          提 交
        </wd-button>
      </view>
    </wd-form>
  </view>
</template>

<style lang="scss">
</style>
